package cn.org.xwb.bookmall.model.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.org.xwb.bookmall.model.po.User;
import cn.org.xwb.bookmall.model.mapper.UserMapper;
import cn.org.xwb.bookmall.model.po.UserAllInfo;
import cn.org.xwb.bookmall.model.properties.AccountProp;
import cn.org.xwb.bookmall.model.service.IUserService;
import cn.org.xwb.bookmall.model.utils.AccountUtil;
import cn.org.xwb.common.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 账户表 服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-11-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private AccountProp accountProp;

    @Autowired
    private AccountUtil accountUtil;

    /**
     * 根据邮箱查询用户
     *
     * @param mail
     * @return
     */
    @Override
    public UserAllInfo findUserByMail(String mail) {
        // 根据邮箱查询用户
        // LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(User::getMail, mail);
        // return baseMapper.selectOne(queryWrapper);
        return baseMapper.selectUserAllInfoByMail(mail);
    }

    /**
     * 根据邮箱查找用户，如果用户不存在则创建用户并返回
     *
     * @param mail
     * @return null-账号被禁用
     */
    @Override
    public UserAllInfo findAndGenUserByMail(String mail) {
        // 根据邮箱查询用户
        UserAllInfo userAllInfo = findUserByMail(mail);
        // 用户不存在，创建用户
        if (Objects.isNull(userAllInfo)) {
            User user = genUserByMail(mail);
            // 新用户入库
            baseMapper.insert(user);
            userAllInfo = findUserByMail(mail);
        }
        // 账号被禁用
        if (userAllInfo.getDisabled()) return null;
        return userAllInfo;
    }

    /**
     * 根据邮箱生成用户
     *
     * @param mail
     * @return
     */
    private User genUserByMail(String mail) {
        String account = accountUtil.genAccount();
        return new User(
                null,
                accountProp.getDefaultAvatar(),
                accountProp.getDefaultAvatarBg(),
                account,
                account,
                null,
                RandomUtil.genRandNumLowerUpperStr(accountProp.getPwdSaltLen()),
                mail,
                false,
                DateUtil.date(),
                false
        );
    }
}
